package com.niit.mobileDevide.numofapp;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class NumOfAppReducer extends Reducer<Text, NumOfAppBean, Text, NumOfAppBean> {

    @Override
    protected void reduce(Text key, Iterable<NumOfAppBean> values, Context context) throws IOException, InterruptedException {
        // 用于存储 numAppsInstalled 字段的值
        List<NumOfAppBean> numAppsInstalledList = new ArrayList<>();

        // 遍历所有记录，添加到 numAppsInstalledList 中
        for (NumOfAppBean val : values) {
            numAppsInstalledList.add(val);
        }

        if (!numAppsInstalledList.isEmpty()) {
            // 对 numAppsInstalled 进行排序，按降序排列
            Collections.sort(numAppsInstalledList, (a, b) -> Integer.compare(b.getNumAppsInstalled(), a.getNumAppsInstalled()));

            // 取出 numAppsInstalled 的前三名
            List<NumOfAppBean> top3NumAppsInstalled = numAppsInstalledList.stream()
                    .limit(3)
                    .collect(Collectors.toList());

            // 输出前三名
            for (NumOfAppBean bean : top3NumAppsInstalled) {
                context.write(new Text(key.toString() + "_Top3"), bean);
            }

            // 对 numAppsInstalled 进行排序，按升序排列
            Collections.sort(numAppsInstalledList, (a, b) -> Integer.compare(a.getNumAppsInstalled(), b.getNumAppsInstalled()));

            // 取出 numAppsInstalled 的后三名
            List<NumOfAppBean> bottom3NumAppsInstalled = numAppsInstalledList.stream()
                    .limit(3)
                    .collect(Collectors.toList());

            // 输出后三名
            for (NumOfAppBean bean : bottom3NumAppsInstalled) {
                context.write(new Text(key.toString() + "_Bottom3"), bean);
            }
        }
    }
}